<?php

namespace yifang\lib;

use yifang\App;
use yifang\container\Container;

/**
 * 配置管理类
 */
class Config
{
    /**
     * 配置参数
     * @var array
     */
    protected $config=array();

    /**
     * 插件配置参数
     * @var array
     */
    protected $pluginConfig=array();

    /**
     * 配置文件目录
     * @var string
     */
    protected $path;

    /**
     * 配置文件后缀
     * @var string
     */
    protected $ext;

    /**
     * 构造方法
     * @access public
     */
    public function __construct($path = null,$ext = '.php')
    {
        $this->path = $path ?: '';
        $this->ext  = $ext;
    }

    public static function __make(App $app)
    {
        $path = $app->getConfigPath();
        $ext  = $app->getConfigExt();
        return new static($path, $ext);
    }

    /**
     * 加载配置文件（多种格式）
     * @access public
     * @param  string $file 配置文件名
     * @param  string $type 1 merge,2 融合
     * @param  string $name 一级配置名
     */
    public function load($file)
    {
        if (is_file($file)) {
            $filename = $file;
        } elseif (is_file($this->path . $file . $this->ext)) {
            $filename = $this->path . $file . $this->ext;
        }
        if (isset($filename)) {
            $result=$this->parse($filename);
            return $result;
        }else{
            return [];
        }
    }

    /**
     * 解析配置文件
     * @access public
     * @param  string $file 配置文件名
     * @param  string $name 一级配置名
     * @return array
     */
    public function parse($file)
    {
        $type   = pathinfo($file, PATHINFO_EXTENSION);
        $config = [];
        switch ($type) {
            case 'php':
                $config = include $file;
                break;
            case 'yml':
            case 'yaml':
                if (function_exists('yaml_parse_file')) {
                    $config = yaml_parse_file($file);
                }
                break;
            case 'ini':
                $config = parse_ini_file($file, true, INI_SCANNER_TYPED) ?: [];
                break;
            case 'json':
                $config = json_decode(file_get_contents($file), true);
                break;
        }
        return is_array($config) ? $config : [];
    }

    /**
     * 初始化配置
     */
    public function loader($loadDir,$type=1){
        foreach($loadDir as $dir){
            if(is_dir($dir)){
                $dir=rtrim($dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
                $funcs=glob(parseDir($dir)."*".$this->ext);
                if($funcs && is_array($funcs)){
                    foreach($funcs as $file){
                        $name=strtolower(pathinfo($file, PATHINFO_FILENAME));
                        $data=$this->load($file);
                        $this->set($data,$name,$type);
                    }
                }
            }
        }
    }

    /**
     * 设置配置参数 name为数组则为批量设置
     * @access public
     * @param  array  $config 配置参数
     * @param  string $name 配置名
     * @return array
     */
    public function set($config, $name = null,$type=1)
    {
        if(is_string($config)){
            $config=getMap($config,$name);
            $result = arrFusion($this->config, array_change_key_case($config));
            $this->config =$result;
        }else{
            if (!empty($name)) {
                if (isset($this->config[$name])) {
                    if($type=="1"){
                        $result=array_merge($this->config[$name],$config);
                    }else{
                        $result=arrFusion($this->config[$name],$config);
                    }
                } else {
                    $result = $config;
                }
                $this->config[$name] = $result;
            } else {
                if($type=="1"){
                    $result = array_merge($this->config, array_change_key_case($config));
                }else{
                    $result = arrFusion($this->config, array_change_key_case($config));
                }
                $this->config =$result;
            }
        }
        return $result;
    }

    /**
     * 检测配置是否存在
     * @access public
     * @param  string $name 配置参数名（支持多级配置 .号分割）
     * @return bool
     */
    public function has($name)
    {
        if (false === strpos($name, '.') && !isset($this->config[strtolower($name)])) {
            return false;
        }
        return !is_null($this->get($name));
    }

    /**
     * 获取一级配置
     * @access protected
     * @param  string $name 一级配置名
     * @return array
     */
    protected function pull($name)
    {
        $name = strtolower($name);
        return $this->config[$name] ?? [];
    }

    /**
     * 获取配置参数 为空则获取所有配置
     */
    public function get($name = null, $default = null)
    {
        // 无参数时获取所有
        if (empty($name)) {
            return $this->config;
        }
        if (false === strpos($name, '.')) {
            return $this->pull($name);
        }

        $name    = explode('.', $name);
        $name[0] = strtolower($name[0]);
        $config  = $this->config;

        // 按.拆分成多维数组进行判断
        foreach ($name as $val) {
            if (isset($config[$val])) {
                $config = $config[$val];
            } else {
                return $default;
            }
        }
        return $config;
    }

    /**
     * 插件加载配置
     */
    public function pluginLoader($loadDir,$prefix){
        foreach($loadDir as $dir){
            if(is_dir($dir)){
                $dir=rtrim(parseDir($dir), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
                $funcs=glob($dir."*".$this->ext);
                if($funcs && is_array($funcs)){
                    foreach($funcs as $file){
                        $name=strtolower(pathinfo($file, PATHINFO_FILENAME));
                        $data=$this->load($file);
                        $this->setPlugin($data,$prefix,$name);
                    }
                }
            }
        }
    }

    /**
     * 插件加载文件
     */
    public function pluginLoaderFile($fileList=array()){
        //遍历配置目录
        if($fileList){
            foreach($fileList as $file){
                if(is_file($file)){
                    $fileName=strtolower(basename($file,".php"));
                    $tmp=@include $file;
                    if(is_array($tmp)){
                        if(isset($this->pluginConfig[$fileName])){
                            $this->pluginConfig[$fileName]=arrFusion($this->pluginConfig[$fileName],$tmp);
                        }else{
                            $this->pluginConfig[$fileName]=$tmp;
                        }
                    }
                }
            }
        }
    }

    /**
     * 设置配置参数 name为数组则为批量设置
     * @access public
     * @param  array  $config 配置参数
     * @param  string $name 配置名
     * @return array
     */
    public function setPlugin($config,$prefix,$name = null)
    {
        if (!empty($name)) {
            if (isset($this->pluginConfig[$prefix][$name])) {
                $result=arrFusion($this->pluginConfig[$prefix][$name],$config);
            } else {
                $result = $config;
            }
            $this->pluginConfig[$prefix][$name] = $result;
        } else {
            if (isset($this->pluginConfig[$prefix])) {
                $result = arrFusion($this->pluginConfig[$prefix], array_change_key_case($config));
            }else{
                $result = array_change_key_case($config);
            }
            $this->pluginConfig[$prefix]=$result;
        }
        return $result;
    }

    /**
     * 检测配置是否存在
     * @access public
     * @param  string $name 配置参数名（支持多级配置 .号分割）
     * @return bool
     */
    public function hasPlugin($name)
    {
        if (false === strpos($name, '.') && !isset($this->pluginConfig[strtolower($name)])) {
            return false;
        }
        return !is_null($this->getPlugin($name));
    }

    /**
     * 获取一级配置
     * @access protected
     * @param  string $name 一级配置名
     * @return array
     */
    protected function pullPlugin($name)
    {
        $name = strtolower($name);
        return $this->pluginConfig[$name] ?? [];
    }

    /**
     * 获取配置
     * @param $name
     * @return mixed
     */
    public function getPlugin($name,$default = null)
    {
        // 无参数时获取所有
        if (empty($name)) {
            return $this->pluginConfig;
        }
        if (false === strpos($name, '.')) {
            return $this->pullPlugin($name);
        }

        $name    = explode('.', $name);
        $name[0] = strtolower($name[0]);
        $config  = $this->pluginConfig;

        // 按.拆分成多维数组进行判断
        foreach ($name as $val) {
            if (isset($config[$val])) {
                $config = $config[$val];
            } else {
                return $default;
            }
        }
        return $config;
    }
}